package com.example.final_project.controller;

import com.example.final_project.entity.TermBook;
import com.example.final_project.service.TermBookService;
import com.example.final_project.service.BookService;
import com.example.final_project.entity.Book;
import com.example.final_project.entity.TermBookBatchAddDTO;
import com.example.final_project.entity.TermBookDetailDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/termbook")
public class TermBookController {
    @Autowired
    private TermBookService termBookService;

    @Autowired
    private BookService bookService;

    @GetMapping("/list")
    public String list(Model model) {
        List<TermBook> termBooks = termBookService.getAllTermBooks();
        model.addAttribute("termBooks", termBooks);
        return "termbook/list";
    }

    @GetMapping("/add")
    public String addPage() {
        return "termbook/add";
    }

    @PostMapping("/add")
    @ResponseBody
    public String addBatch(@RequestBody TermBookBatchAddDTO batchAddDTO) {
        try {
            // 先查出当前学期+专业下所有已存在的教材ID
            List<TermBook> existList = termBookService.getAllTermBooks();
            java.util.Set<Long> existBookIds = new java.util.HashSet<>();
            for (TermBook tb : existList) {
                if (batchAddDTO.getTerm().equals(tb.getTerm()) && batchAddDTO.getMajor().equals(tb.getMajor())) {
                    existBookIds.add(tb.getBookId());
                }
            }
            // 校验本次提交是否有重复教材
            for (TermBookDetailDTO detail : batchAddDTO.getDetails()) {
                if (existBookIds.contains(detail.getBookId())) {
                    return "同一学期同一专业不能重复添加同一本教材";
                }
            }
            for (TermBookDetailDTO detail : batchAddDTO.getDetails()) {
                TermBook termBook = new TermBook();
                termBook.setTerm(batchAddDTO.getTerm());
                termBook.setMajor(batchAddDTO.getMajor());
                termBook.setBookId(detail.getBookId());
                // 自动补全bookName
                Book book = bookService.getById(detail.getBookId());
                if (book != null) {
                    termBook.setBookName(book.getName());
                }
                termBookService.addTermBook(termBook);
            }
            return "success";
        } catch (Exception e) {
            e.printStackTrace();
            return "error";
        }
    }

    @GetMapping("/edit/{id}")
    public String editPage(@PathVariable Long id, Model model) {
        TermBook termBook = termBookService.getTermBookById(id);
        model.addAttribute("termBook", termBook);
        return "termbook/edit";
    }

    @PostMapping("/edit")
    public String edit(TermBook termBook) {
        termBookService.updateTermBook(termBook);
        return "redirect:/termbook/list";
    }

    @GetMapping("/delete/{id}")
    public String delete(@PathVariable Long id) {
        termBookService.deleteTermBook(id);
        return "redirect:/termbook/list";
    }

    @GetMapping("/detail/{id}")
    public String detail(@PathVariable Long id, Model model) {
        TermBook termBook = termBookService.getTermBookById(id);
        model.addAttribute("termBook", termBook);
        return "termbook/detail";
    }

    @GetMapping("/api/allBooks")
    @ResponseBody
    public List<Book> getAllBooks() {
        return bookService.getAll();
    }

    @GetMapping("/api/list")
    @ResponseBody
    public Map<String, Object> apiList(
            @RequestParam(required = false) String bookName,
            @RequestParam(required = false) String term,
            @RequestParam(required = false) String major,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        List<TermBook> all = termBookService.getAllTermBooks();
        // 简单条件过滤
        List<TermBook> filtered = new java.util.ArrayList<>();
        for (TermBook tb : all) {
            boolean match = true;
            if (bookName != null && !bookName.isEmpty() && (tb.getBookName() == null || !tb.getBookName().contains(bookName))) match = false;
            if (term != null && !term.isEmpty() && (tb.getTerm() == null || !tb.getTerm().contains(term))) match = false;
            if (major != null && !major.isEmpty() && (tb.getMajor() == null || !tb.getMajor().equals(major))) match = false;
            if (match) filtered.add(tb);
        }
        int total = filtered.size();
        int from = (pageNum - 1) * pageSize;
        int to = Math.min(from + pageSize, total);
        List<TermBook> pageList = from < total ? filtered.subList(from, to) : new java.util.ArrayList<>();
        Map<String, Object> result = new HashMap<>();
        result.put("list", pageList);
        result.put("total", total);
        return result;
    }

    @PostMapping("/api/deleteBooks")
    @ResponseBody
    public String deleteBooks(@RequestBody Map<String, Object> params) {
        String term = (String) params.get("term");
        String major = (String) params.get("major");
        List<Integer> bookIds = (List<Integer>) params.get("bookIds");
        if (term == null || major == null || bookIds == null || bookIds.isEmpty()) return "error";
        List<TermBook> all = termBookService.getAllTermBooks();
        for (TermBook tb : all) {
            if (term.equals(tb.getTerm()) && major.equals(tb.getMajor()) && bookIds.contains(tb.getBookId().intValue())) {
                termBookService.deleteTermBook(tb.getId());
            }
        }
        return "success";
    }

    @PostMapping("/api/editGroup")
    @ResponseBody
    public String editGroup(@RequestBody Map<String, String> params) {
        String oldTerm = params.get("oldTerm");
        String oldMajor = params.get("oldMajor");
        String newTerm = params.get("newTerm");
        String newMajor = params.get("newMajor");
        if (oldTerm == null || oldMajor == null || newTerm == null || newMajor == null) return "error";
        // 校验目标学期+专业是否已存在
        List<TermBook> all = termBookService.getAllTermBooks();
        boolean exist = false;
        for (TermBook tb : all) {
            if (newTerm.equals(tb.getTerm()) && newMajor.equals(tb.getMajor())) {
                exist = true;
                break;
            }
        }
        if (exist) return "已存在同一学期同一专业，不能进行替换";
        for (TermBook tb : all) {
            if (oldTerm.equals(tb.getTerm()) && oldMajor.equals(tb.getMajor())) {
                tb.setTerm(newTerm);
                tb.setMajor(newMajor);
                termBookService.updateTermBook(tb);
            }
        }
        return "success";
    }

    @GetMapping("/api/byTermMajor")
    @ResponseBody
    public List<Map<String, Object>> getByTermMajor(@RequestParam String term, @RequestParam String major) {
        List<TermBook> all = termBookService.getAllTermBooks();
        List<Map<String, Object>> result = new java.util.ArrayList<>();
        for (TermBook tb : all) {
            if (term.equals(tb.getTerm()) && major.equals(tb.getMajor())) {
                Book book = bookService.getById(tb.getBookId());
                Map<String, Object> map = new java.util.HashMap<>();
                map.put("bookId", tb.getBookId());
                map.put("bookName", tb.getBookName());
                if (book != null) {
                    map.put("isbn", book.getIsbn());
                    map.put("author", book.getAuthor());
                    map.put("publisher", book.getPublisher() != null ? book.getPublisher().getName() : "");
                    map.put("price", book.getPrice());
                } else {
                    map.put("isbn", "");
                    map.put("author", "");
                    map.put("publisher", "");
                    map.put("price", "");
                }
                result.add(map);
            }
        }
        return result;
    }

    @GetMapping("/listByUser")
    public String listByUser(@RequestParam(value = "term", required = false) String term, HttpSession session, Model model) {
        com.example.final_project.entity.User user = (com.example.final_project.entity.User) session.getAttribute("user");
        String major = user != null ? user.getDepartment() : null;
        model.addAttribute("user", user);
        model.addAttribute("term", term);
        model.addAttribute("major", major);
        // 页面渲染时前端通过接口获取教材列表
        return "termbook/list_by_user";
    }
} 